// vi:si:et:sw=4:sts=4:ts=4
package cat.hex.trainoid;

import java.util.Date;

import android.content.Context;
import android.database.Cursor;
import android.util.Log;

public class User
{
    public static final String BIRTHDAY_FORMAT = "yyyy/MM/dd";

    protected String name;
    protected int weight;
    protected int height;
    protected float totalTime;
    protected float totalDistance;
    protected Date birthday;

    private DbAdapter mDbHelper;	
    private final Context mCtx;

	static final private String tag = "User"; // for Log
    
    public User(long userId, Context ctx)
    {
        this.mCtx = ctx;

        mDbHelper = new DbAdapter(mCtx);
        mDbHelper.open();
        Cursor userData = mDbHelper.getUserData(userId);

        this.name = userData.getString(0);
        this.weight = userData.getInt(1);
        this.height = userData.getInt(2);

        this.totalDistance = userData.getFloat(3);
        this.totalTime = userData.getFloat(4);

        //this.birthday = userData.getLong(3);
        
        // temporary
//        if (totalDistance == 0)
        {
        	calculateTotals();
        }

    }

    public String getName()
    {
        return name;
    }

    public float getTotalTime()
    {
        return totalTime;
    }

    private void calculateTotals()
    {
		Cursor cur = mDbHelper.fetchAllTracks();
		Track t;
		totalDistance = 0;
		totalTime = 0;
		
        for (cur.moveToFirst(); cur.isAfterLast() == false; cur.moveToNext())
        {
             t = new Track(cur.getLong(0), mCtx);
             totalDistance += t.getTotalDistance();
             totalTime += t.getTotalTime();
             
             Log.v(tag, "********** track total time: " + t.getTotalTime());
        }
        cur.close();
        
        mDbHelper.updateUserDistance(trainoid.DEFAULT_USER_ID, totalDistance);
        mDbHelper.updateUserTime(trainoid.DEFAULT_USER_ID, totalTime);

    }

    private void calculateTotalDistance()
    {
		Cursor cur = mDbHelper.fetchAllTracks();
		Track t;
		
        for (cur.moveToFirst(); cur.isAfterLast() == false; cur.moveToNext())
        {
             t = new Track(cur.getLong(0), mCtx);
             totalDistance += t.getTotalDistance();
        }
        cur.close();
    }

    public float getTotalDistance()
    {
    	if (totalDistance == 0)
    		calculateTotalDistance();
    		
        return totalDistance;
    }

    public int getWeight()
    {
        return weight;
    }

    public int getHeight()
    {
        return height;
    }
    
    public float addDistance(float distance)
    {
    	return (totalDistance += distance);
    }
}
